// components/search/search.js

const app = getApp()
const db = wx.cloud.database()

Component({
  options: {
    styleIsolation: 'apply-shared'
  },
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    isFocus:false,
    historyList : [],
    searchList : [],
    inputValue:''
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //获取焦点时触发
    handleFocus(){

      wx.getStorage({//获取本地存储
        key: "searchHistory",
        success: (res)=> {
          this.setData({
            historyList : res.data
          });
        }
      })

      this.setData({
        isFocus : true
      });
    },
    //点击取消按钮
    handleCancel(){
      this.setData({
        isFocus: false
      });
    },
    //按下回车时
    handleConfirm(ev){
      let value = ev.detail.value;
      let cloneHistoryList = [...this.data.historyList];
      cloneHistoryList.unshift(value);
      wx.setStorage({//设置本地存储
        key: "searchHistory",
        data: [...new Set(cloneHistoryList)]//ES6的去重并写入数据
      });
      this.changeSearchList(value);
      this.setData({//按下回车清空input框内容
        inputValue: ''
      })
    },
    //删除历史记录
    handleHistoryDelete(){
      wx.removeStorage({//清除本地缓存
        key: 'searchHistory',
        success:(res)=>{
          this.setData({
            historyList : []
          });
        }
      })
    },
    //搜索列表的更新
    changeSearchList(value){
      db.collection('users').where({
        nickName: db.RegExp({//正则表达式
          regexp: value,
          options: 'i'//忽略大小写
        })
      }).field({
        userPhoto : true,
        nickName : true
      }).get().then((res)=>{
        this.setData({
          searchList : res.data
        });
      });
    },
    //点击历史记录的子节点
    handleHistoryItemDel(ev){
      let value = ev.target.dataset.text;
      this.changeSearchList(value);
    }
  }
})
